<?php
namespace hema\storage;

use hema\storage\engine\Aliyun;
use hema\storage\engine\Local;
use hema\storage\engine\Qcloud;
use hema\storage\engine\Qiniu;

/**
 * 存储模块驱动
 */
class Driver
{
    private $engine;    // 当前引擎类
    private $cloud = [
        'qiniu' => '七牛',
        'aliyun' => '阿里',
        'qcloud' => '腾讯'
    ];
    
    /**
     * 存储引擎类列表
     */
    const ENGINE_CLASS_LIST = [
        'local' => Local::class,
        'qiniu' => QINIU::class,
        'aliyun' => Aliyun::class,
        'qcloud' => Qcloud::class
    ];

    /**
     * 构造方法
     * @param null|string $storage 指定存储方式
     */
    public function __construct($storage)
    {
        // 实例化当前存储引擎
        $config = get_addons_config($storage);
        $class = self::ENGINE_CLASS_LIST[$storage];
        $this->engine = new $class($storage, $config);
        if($storage != 'local' AND !$config){
            die(json_encode(['code' => 0, 'msg' => '未安装《' . $this->cloud[$storage] .'云存储》插件']));
        }
    }

    /**
     * 设置上传的文件信息
     * @param string $name
     * @return mixed
     */
    public function setUploadFile($name = 'iFile')
    {
        return $this->engine->setUploadFile($name);
    }

    /**
     * 设置上传的文件信息
     * @param string $filePath
     * @return mixed
     */
    public function setUploadFileByReal(string $filePath)
    {
        return $this->engine->setUploadFileByReal($filePath);
    }

    /**
     * 设置上传文件的验证规则
     * @param array $rules
     * @return mixed
     */
    public function setValidationScene(array $rules = [])
    {
        return $this->engine->setValidationScene($rules);
    }

    /**
     * 执行文件上传
     */
    public function upload()
    {
        return $this->engine->upload();
    }

    /**
     * 执行文件删除
     * @param string $filePath
     * @return mixed
     */
    public function delete(string $filePath)
    {
        return $this->engine->delete($filePath);
    }

    /**
     * 获取错误信息
     * @return mixed
     */
    public function getError()
    {
        return $this->engine->getError();
    }

    /**
     * 返回保存的文件信息
     * @return mixed
     */
    public function getSaveFileInfo()
    {
        return $this->engine->getSaveFileInfo();
    }

}
